package korkd.tower;

import java.util.Stack;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.camera.hud.HUD;
import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.ITouchArea;

public class SceneManager {
	
	public static SceneManager INSTANCE;
	
	private Engine mEngine;
	private Camera mCamera;
	private Scene mCurrentScene;
	private Stack<Scene> mSceneList;
	private HUD mCurrentHUD;
	private Stack<HUD> mHUDList;

	SceneManager(Engine pEngine, Camera pCamera)
	{
		mEngine = pEngine;
		mCamera = pCamera;
		mSceneList = new Stack<Scene>();
		mHUDList = new Stack<HUD>();
		mCurrentScene = null;
	}
	
	public void addScene(Scene pScene)
	{
		if(!mSceneList.contains(pScene))
		{
			mSceneList.push(pScene);
		}
		
		mCurrentScene = pScene;
		mEngine.setScene(mCurrentScene);
	}
	
	public void addHUD(HUD pHUD)
	{
		if(!mHUDList.contains(pHUD))
		{
			mHUDList.push(pHUD);
		}
		
		mCurrentHUD = pHUD;
		mCamera.setHUD(mCurrentHUD);
	}
	
	public void addScene(Scene pScene, HUD pHUD)
	{
		addScene(pScene);
		addHUD(pHUD);
	}
	
	public void removeScene()
	{
		Scene tempScene = mSceneList.pop();
		
		if(!mSceneList.isEmpty())
		{
			addScene(mSceneList.lastElement());
		}
		
		mCurrentScene.detachChild(tempScene);
	}
	
	public void removeHUD()
	{
		mHUDList.pop();
		
		if(!mHUDList.isEmpty())
		{
			addHUD(mHUDList.lastElement());
		}
	}
	
	public void disableHUD()
	{
		if(mCurrentHUD != null)
		{
			mCurrentHUD.setCamera(null);
		}
	}
	
	public void enableHUD()
	{
		if(mCurrentHUD != null)
		{
			mCurrentHUD.setCamera(mCamera);
		}
	}
	
	public void clear()
	{
		removeScene();
		removeHUD();
	}
	
	public void attachToCurrent(IEntity pEntity)
	{
		mCurrentScene.attachChild(pEntity);
	}
	
	public void removeFromCurrent(IEntity pEntity)
	{
		mCurrentScene.detachChild(pEntity);
	}
	
	public void registerTouchArea(ITouchArea pTouchArea)
	{
		mCurrentScene.registerTouchArea(pTouchArea);
	}
	
	public void setChildScene(Scene pScene)
	{
		mCurrentScene.setChildScene(pScene);
	}

	public void clearChildScene() 
	{
		mCurrentScene.clearChildScene();	
	}
}
